package com.dimples.security.filter;

import com.dimples.common.constant.StrPool;
import com.dimples.common.entity.SecurityUser;
import com.dimples.common.enums.CodeMsgEnum;
import com.dimples.common.service.DimplesJwtTokenServiceImpl;
import com.dimples.common.transport.Result;
import com.dimples.security.entity.SecurityUserDetails;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import lombok.RequiredArgsConstructor;

/**
 * @author zhongyj <1126834403@qq.com><br/>
 * @date 2021/6/21
 */
@SuppressWarnings("NullableProblems")
@Configuration
@RequiredArgsConstructor
public class DimplesTokenFilter extends OncePerRequestFilter {

    private final DimplesJwtTokenServiceImpl tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 尝试拿 token 中的 user; 若是没有 token 或者拿 user 时出现异常，那么 user 为 null
        SecurityUser securityUser = tokenService.getLoginUserFromToken(request);
        if (ObjectUtil.isEmpty(securityUser) && StrUtil.isNotBlank(tokenService.parseToken(request))) {
            throw new CredentialsExpiredException("token过期");
        }

        // 如果上面解析 token 成功并且拿到了 user 并且本次会话的权限还未被写入
        if (securityUser != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            this.tokenService.validateToken(securityUser);
            // 生成通过认证
            SecurityUserDetails securityUserDetails = SecurityUserDetails.convert(securityUser);
            UsernamePasswordAuthenticationToken authentication
                    = new UsernamePasswordAuthenticationToken(securityUserDetails, null, AuthorityUtils.commaSeparatedStringToAuthorityList(StrUtil.join(StrPool.COMMA, securityUser.getAuthorities())));
            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            // 将权限写入本次会话
            SecurityContextHolder.getContext().setAuthentication(authentication);

            if (!securityUser.isEnabled()) {
                Result.writer(CodeMsgEnum.ACCOUNT_FREEZE.getCode(), CodeMsgEnum.ACCOUNT_FREEZE.getMessage());
                return;
            }
        }
        chain.doFilter(request, response);
    }

}
